//
//  MLZLogINViewController.m
//  MotherLover
//
//  Created by lanou on 16/1/8.
//  Copyright © 2016年 zj. All rights reserved.
//

#import "MLZLogINViewController.h"
#import "MLZLogInView.h"
#import "MLZRegiserViewController.h"
#import "MLZInfoTableViewCell.h"
#import "HFStretchableTableHeaderView.h"
#import <TencentOpenAPI/TencentOAuth.h>

@interface MLZLogINViewController ()<TencentSessionDelegate>
{
    UIButton *qqLoginBtn;
    TencentOAuth *tencentOAuth;
    NSArray *permissions;

}

@end
@interface MLZLogINViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) MLZLogInView *loginView;
@property (nonatomic, strong) UITableView *infoTableView;
@property (nonatomic, strong) HFStretchableTableHeaderView *hendview;
@property (nonatomic, strong)  UIButton *registerButton;
@property (nonatomic, strong)  UIButton *image ;

@end

@implementation MLZLogINViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
 
   
if([BmobUser getCurrentUser]){
    [self addInfoView];
    
    }else {
    
    [self addViewsssss];
    //初始化TencentOAuth 对象 appid来自应用宝创建的应用， deletegate设置为self  一定记得实现代理方法
    tencentOAuth = [[TencentOAuth alloc]initWithAppId:@"1105101178" andDelegate:self];
    //设置需要的权限列表，此处尽量使用什么取什么
    permissions= [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t", nil];
                
    }
    [self addbutton];
    [self datapassing];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden= YES;
}
-(void)viewWillAppear:(BOOL)animated{
   
   
    [self loadView];
    [self viewDidLoad];

}
-(void)addbutton{


    //注册或者注销
    
    
    UIButton *registerButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    registerButton.frame = CGRectMake(KW-50, 20, 40, 40);
    
    if([BmobUser getCurrentUser]){
        [registerButton setTitle:@"注销" forState:(UIControlStateNormal)];
    }else {
        [registerButton setTitle:@"注册" forState:(UIControlStateNormal)];}
    [registerButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [registerButton addTarget:self action:@selector(regiserAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:registerButton];

}



- (void)datapassing{
    NSUserDefaults *userqq = [NSUserDefaults standardUserDefaults];
   NSString *name = [userqq objectForKey:@"username"];
    NSString *imageIcon = [userqq objectForKey:@"imageIcon"];
    if([[BmobUser getCurrentUser].username isEqualToString:name]){
   
        _UerName = name;
        _imgUrl = imageIcon;
    
    
    
    }else{
    
        BmobUser *user = [BmobUser getCurrentUser];
        
        
        _UerName = user.username;
        _imgUrl = user.email;
        
      
    
    
    }
    
    
       [_infoTableView reloadData];







}

- (void)addInfoView{
    
    
 
    _infoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KW, KH-64) style:(UITableViewStylePlain)];
    _infoTableView.delegate = self;
    _infoTableView.dataSource = self;
    _infoTableView.rowHeight = 70;
    [self.view addSubview:_infoTableView];
    //背景
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
    bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    bgImageView.clipsToBounds = YES;
    bgImageView.image = [UIImage imageNamed:@"hashiqi"];
    
       
    
   
    
    
    
  
    //背景之上的内容
    _image = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _image.frame =CGRectMake(bgImageView.width/3*2, bgImageView.bottom-bgImageView.width/3, bgImageView.width/3, bgImageView.width/3);
    [_image addTarget:self  action:@selector(imageAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_image.layer setCornerRadius:bgImageView.width/3/2];
    _image.layer.masksToBounds= YES;
    if(_imgUrl.length==0){
    
        //[_image setImage:[UIImage imageNamed:@"xiaotou"] forState:(UIControlStateNormal)] ;
    }else{
    [_image sd_setBackgroundImageWithURL:[NSURL URLWithString:_imgUrl] forState:(UIControlStateNormal)];
    }
    
    
    _hendview= [[HFStretchableTableHeaderView alloc]init];
    [self.hendview stretchHeaderForTableView:self.infoTableView withView:bgImageView  subViews:_image];
    
    
    
}
//点击更换头像
-(void)imageAction:(UIButton*)button{

    NSLog(@"添加头像");
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //如果有相机系统
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
            
        }
        else
        {
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"你的设备没有摄像头" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertVc addAction:otherAction];
            [self presentViewController:alertVc animated:YES completion:nil];
            
        }
    }];
    UIAlertAction *actionPhoto = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //如果有相册
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;//是否可以编辑
            //打开相册选择照片
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //模态进入相册
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alertVc addAction:otherAction];
    [alertVc addAction:actionPhoto];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];
    
    









}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [_image setBackgroundImage:[info objectForKey:UIImagePickerControllerOriginalImage] forState:(UIControlStateNormal)];
    
    
    
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - stretchableTable delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.hendview scrollViewDidScroll:scrollView];
}

- (void)viewDidLayoutSubviews
{
    [self.hendview resizeView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{


    return 1;

}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *identifier = @"ZJCell";
    MLZInfoTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[MLZInfoTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }

    
    NSArray *array =@[@"昵称"];
    cell.imageIcon.text = array[indexPath.row];
    cell.lableUser.text = _UerName;
    
    return cell;

}
#pragma mark---------上是登陆之后的界面 下面是登陆界面;
- (void)addViewsssss{
 
    
    
    
    self.loginView = [[MLZLogInView alloc]initWithFrame:CGRectMake(0, 64, KW, KH)];
    [_loginView.loginButt addTarget:self action:@selector(loginButtAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_loginView.qqLoginBtn addTarget:self action:@selector(qqButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_loginView.wbLoginBtn addTarget:self action:@selector(wbButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:_loginView];
    
    
    
}
- (void)loginButtAction:(UIButton*)button{
   [BmobUser loginInbackgroundWithAccount:_loginView.mailTF.text andPassword:_loginView.passwordTF.text block:^(BmobUser *user, NSError *error) {
    
    if(!error){
        NSLog(@"%@",user);
       NSLog(@"登陆成功");
        
        [_loginView.mailTF resignFirstResponder];
          [_loginView.passwordTF resignFirstResponder];
        [self loadView];
        [self viewDidLoad];
        [self viewWillAppear:YES];
    
    }else {
   
        [self alertActionWithTitle:@"错误" message:@"用户名或密码错误" other:@"确定"];
   
    }
    
}];
    
}
#pragma mark -------qq登陆------------
- (void)qqButtonAction:(UIButton *)button
{
    NSLog(@"loginAct");
    [tencentOAuth authorize:permissions inSafari:NO];
}
//登陆完成调用
- (void)tencentDidLogin
{
    
    [self alertActionWithTitle: @"登录完成" message:nil other:@"确定"];
    NSDictionary *dic = @{@"access_token":tencentOAuth.accessToken,@"uid":tencentOAuth.openId,@"expirationDate":tencentOAuth.expirationDate};
    [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:BmobSNSPlatformQQ block:^(BmobUser *user, NSError *error) {
       
        NSLog(@"%@ user",user);
        NSLog(@"%@ error", error);
        [self loadView];
        [self viewDidLoad];
        [self viewWillAppear:YES];
    }];
  
    if (tencentOAuth.accessToken && 0 != [tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        NSLog(@"%s %d %@ %@ %@",__FUNCTION__,__LINE__,tencentOAuth.accessToken,tencentOAuth.expirationDate,tencentOAuth.openId);
        
        [tencentOAuth getUserInfo];
    }
    else
    {
//        tokenLable.text = @"登录不成功 没有获取accesstoken";
    }
}

//非网络错误导致登录失败：
-(void)tencentDidNotLogin:(BOOL)cancelled
{
    NSLog(@"tencentDidNotLogin");
    if (cancelled)
    {
        [self alertActionWithTitle:@"用户取消登录" message:nil other:@"确定"];
        
    }else{
         [self alertActionWithTitle:@"登录失败" message:nil other:@"确定"];
        
    }
}
// 网络错误导致登录失败：
-(void)tencentDidNotNetWork
{
    NSLog(@"tencentDidNotNetWork");
    [self alertActionWithTitle:@"无网络连接，请设置网络" message:nil other:@"确定"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getUserInfoResponse:(APIResponse *)response
{
    NSLog(@"%s %d  respons:%@ ",__FUNCTION__,__LINE__,response.jsonResponse);
    NSDictionary *dic = response.jsonResponse;
    BmobUser*user =    [BmobUser getCurrentUser];
    user.username = [dic objectForKey:@"nickname"];
    
    
    NSUserDefaults *userqq = [NSUserDefaults standardUserDefaults];
    [userqq setObject:[dic objectForKey:@"nickname"] forKey:@"username"];
    [userqq setObject:[dic objectForKey:@"figureurl_qq_2"] forKey:@"imageIcon"];
    //[MLZImageIcon shahandel].username =[dic objectForKey:@"nickname"];
    //[MLZImageIcon shahandel].imageIcon = [dic objectForKey:@"figureurl_qq_2"];
    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        NSLog(@"%@,%@",user,error);
        
        [self datapassing];
    }];
  
// BmobObject *obj = [BmobObject objectWithClassName:[NSString stringWithFormat:@"p%@",[BmobUser getCurrentUser].objectId]];
//    [obj setObject:_UerName forKey:@"name"];
//    [obj setObject:_imgUrl forKey:@"imgUrl"];
//    [obj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
//        NSLog(@"%@",error);
//    }];
    
//  BmobUser*user =    [BmobUser getCurrentUser];
//    user.username = _UerName;
//    user.email = _imgUrl;
//    [user updateInBackground];
    
    [self loadView];
    [self viewDidLoad];
    [self viewWillAppear:YES];
}

#pragma mark -----微博登陆------
- (void)wbButtonAction:(UIButton *)button
{
    
}
- (void)regiserAction:(UIButton*)button{

    if(![BmobUser getCurrentUser]){
    
    MLZRegiserViewController *regiser = [[MLZRegiserViewController alloc]init];
    [self.navigationController pushViewController:regiser animated:YES];
    
    }else {
        
        [BmobUser logout];
        [self loadView];
        [self viewDidLoad];
        [self viewWillAppear:YES];
     
    
    
    }
    

}
- (UIAlertController *)alertActionWithTitle:(NSString *)title message:(NSString *)message other:(NSString *)other
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:nil];
    [alertVc addAction:otherAction];
    [self presentViewController:alertVc animated:YES completion:nil];
    return alertVc;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
